package com.book.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.book.entity.Book;
import com.book.entity.Category;
import com.book.request.getHotBookReq;
import com.book.service.BookService;
import com.book.service.CategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import utils.SecurityUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/book")
public class BookController extends BaseController{
    @Resource
    private BookService bookService;
    @Resource
    private CategoryService categoryService;

    @RequestMapping("/admin/list")
    public ModelAndView adminList(){
        ModelAndView mav=new ModelAndView();
        if(SecurityUtil.getCurrentUser().getUserType().equals("admin")){
            mav.setViewName("admin/book/list");
        }else{
            mav.addObject("权限不足");
            mav.setViewName("common/500");
        }
        return mav;
    }

    @RequestMapping("/list")
    public ModelAndView list(Book book, HttpServletRequest request) throws Exception{
        ModelAndView mav=new ModelAndView();
        int current=getPageNum(request) ;
        int size=10;
        Category category=null;
        if(StringUtils.isNotEmpty(book.getCId())){
            category=categoryService.findById(book.getCId());
        }
        Page books=bookService.getBooksByCId(request.getParameter("cid"),current,size);
        mav.addObject("books", books);
        mav.addObject("category", category);
        mav.setViewName("category");
        return mav;
    }

    @RequestMapping("/search")
    public ModelAndView search(HttpServletRequest request){
        String keyword=request.getParameter("keyword");
        List<Book> books=bookService.search(keyword);
        ModelAndView mav=new ModelAndView();
        mav.addObject("books",books);
        mav.setViewName("search");
        return mav;
    }

    @RequestMapping("/get")
    public ModelAndView get(HttpServletRequest request){
        ModelAndView mav=new ModelAndView();
        int current=getPageNum(request);
        int size=10;
        String id=request.getParameter("id");
        String cid=request.getParameter("cId");
        if(StringUtils.isEmpty(id)){
            mav.addObject("errorMsg", "id不能为空");
            mav.setViewName("/common/500");
        }
        Book book=bookService.selectById(id);
        mav.addObject("categoryBooks", bookService.getBooksByCId(cid,current,size));
        mav.addObject("book", book);
        getHotBookReq req=new getHotBookReq();
        req.setSize(10);
        req.setCurrent(getPageNum(request));
        mav.addObject("hotBooks", bookService.getHotBooks(req));
        mav.setViewName("single-book");
        return mav;
    }

    @RequestMapping("/getPager")
    public Page getPager(Book book, HttpServletRequest request){
        if(StringUtils.isNotEmpty(book.getBName())){
            book.setBName("%"+book.getBName()+"%");
        }
        Page page=new Page();
        page.setCurrent(getPageNum(request));
        page.setSize(getPageSize(request));
        return bookService.selectPage(page);
    }

    @RequestMapping("admin/to_add")
    public ModelAndView toAdd(){
        ModelAndView mav=new ModelAndView();
        if(SecurityUtil.getCurrentUser().getUserType().equals("admin")){
            mav.addObject("book", new Book());//防止前台freemark报错
            mav.setViewName("admin/book/add");
        }else{
            mav.addObject("errorMsg","权限不足，只有管理员才能访问此页面");
        }
        return mav;
    }

    @RequestMapping("admin/save")
    public ModelAndView save(Book book,HttpServletRequest request){
        ModelAndView mav=new ModelAndView();
        if(SecurityUtil.getCurrentUser().getUserType().equals("admin")){
            try{
                bookService.insert(book);
                msg.setSuccessMsg("保存成功");
            }catch(Exception e){
                msg.setErrorMsg("保存失败");
            }
            mav.addObject("msg", msg);
            mav.setViewName("admin/common/jump");
        }else{
            mav.addObject("errorMsg","权限不足，只有管理员才能访问此页面");
            mav.setViewName("common/500");
        }
        return mav;
    }

    @RequestMapping("/admin/to_edit")
    public ModelAndView toEdit(HttpServletRequest request){
        ModelAndView mav=new ModelAndView();
        if(SecurityUtil.getCurrentRole()!=null &&"admin".equals(SecurityUtil.getCurrentRole().getName())){
            String showImgUrl="";
            String bid=get(request, "bid");
            mav.addObject("categories", categoryService.selectList(null));
            mav.addObject("book", bookService.selectById(bid));
            mav.addObject("showImgUrl", showImgUrl);
            mav.setViewName("admin/book/add");
        }else{
            mav.addObject("errorMsg","权限不足，只有管理员才能访问此页面");
            mav.setViewName("common/500");
        }
        return mav;
    }

    @RequestMapping("/admin/remove")
    @ResponseBody
    public Map<String,Object> remove(HttpServletRequest request, HttpServletResponse response){
        String bid=get(request, "bid");
        Map<String,Object> resultMap=new HashMap<String, Object>();
        try{
            bookService.deleteById(bid);
            msg.setSuccessMsg("删除成功");
        }catch(Exception e){
            msg.setErrorMsg("删除失败");
        }
        resultMap.put("msg", msg);
        return resultMap;
    }

    @RequestMapping("user/to_add")
    public ModelAndView userToAdd(){
        ModelAndView mav=new ModelAndView();
        if(SecurityUtil.getCurrentUser()!=null){
            mav.addObject("categories", categoryService.selectList(null));
            mav.addObject("book", new Book());//防止前台freemark报错
            mav.setViewName("addbook");
        }else
            mav.setViewName("login");
        return mav;
    }

    @RequestMapping("user/save")
    public String userSave(Book book,HttpServletRequest request,HttpServletResponse response,ModelMap m){
        String uId=SecurityUtil.getCurrentUser().getUId();
        book.setOwnerId(uId);
        bookService.insert(book);
        msg.setSuccessMsg("保存成功");
        m.put("msg", msg);
        return "addbook";
    }





}
